# -*- coding: utf-8 -*-
# 自动登录远程服务器
import os
import base64
import sys
import paramiko

path = os.path.dirname(os.path.abspath(sys.argv[0]))

def ssh_connect(host_ip, host_port, username, password):
	ssh = paramiko.SSHClient()
	ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
	try:
		ssh.connect(host_ip, host_port, username, password, allow_agent=False, look_for_keys=False)
		print('[INFO]:Connect Successfully...')
	except:
		print('[INFO]:Fail to Connect...')
	while True:
		command = input('Enter the command(<#q> exit):')
		if command.strip() == '#q':
			ssh.close()
			return
		stdin, stdout, stderr = ssh.exec_command(command)
		out_content = stdout.readlines()
		if len(out_content) < 1:
			print('Error:')
			print(stderr.readlines())
		else:
			print('Result:')
			for o in out_content:
				print(o)



def choose_host():
	f = open("{}/data/info.d".format(path))
	hosts = f.readlines()
	hosts_temp = []
	for h in hosts:
		if h.strip():
			hosts_temp.append(h)
	hosts = hosts_temp[:]
	hosts_len = len(hosts)
	if hosts_len <= 0:
		os.system('cls')
		print('[Warning]:No info saved before...')
		return
	while True:
		print('SSH......')
		print('FORMAT:\nAlias UserName@IP: PORT')
		for i in range(0, hosts_len):
			line_list = hosts[i].strip().split(' ')
			print("<{}>: {} |{}@{}: {}|".format(i+1, line_list[4], line_list[2], line_list[0], line_list[1]))
		choice = input('[SSH]:Choose the number or alias(<#q> exit):')
		is_alias = False
		is_num = False
		try:
			choice = int(choice)
			if choice < 1 or choice > hosts_len:
				os.system('cls')
				print('[Warning]:Number inexistence...')
				continue
			line_list = hosts[choice-1].split(' ')
			username = line_list[2]
			password = line_list[3]
			host_ip = line_list[0]
			host_port = line_list[1]
			is_num = True
		except:
			is_alias = True
		if is_alias:
			if choice.strip() == '#q':
				os.system('clear')
				return
			for h in hosts:
				if choice.strip() == h.split(' ')[4].strip():
					line_list = h.split(' ')
					username = line_list[2]
					password = line_list[3]
					host_ip = line_list[0]
					host_port = line_list[1]
					is_num = True
		if not is_num:
			os.system('cls')
			print('[Warning]:Alias inexistence...')
			continue
		# password = base64.decodestring(password)
		print('Start to connect {}@{}...'.format(username, host_ip))
		ssh_connect(host_ip, host_port, username, password)